package www.dianbaozu.com.ui.chat

import androidx.lifecycle.viewModelScope
import com.netease.nim.uikit.api.NIMHelper
import com.netease.nimlib.sdk.RequestCallbackWrapper
import com.netease.nimlib.sdk.ResponseCode
import com.netease.nimlib.sdk.msg.model.RecentContact
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.launch
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.CustomRecentContact
import javax.inject.Inject

/**
 * [Deprecated]
 */
class PrivateLetterViewModel @Inject constructor() : BaseViewModel() {

    val mRecentContactList: SharedFlow<List<CustomRecentContact>>
        get() = _mRecentContactList

    private val _mRecentContactList by lazy {
        MutableSharedFlow<List<CustomRecentContact>>().also { refreshRecentContact() }
    }

    fun refreshRecentContact() {
        NIMHelper.getRecentContact(object :
            RequestCallbackWrapper<List<RecentContact>?>() {
            override fun onResult(code: Int, result: List<RecentContact>?, exception: Throwable?) {
                if (code == ResponseCode.RES_SUCCESS.toInt()) {
                    viewModelScope.launch {
                        val allFriendUnreadCountList = NIMHelper.getAllFriendUnreadCountList()
                        val allFriendsLoginStatus = NIMHelper.allFriendsLoginStatus
                        val customRecentContactList = mutableListOf<CustomRecentContact>()
                        result?.forEach {
                            customRecentContactList.add(
                                CustomRecentContact(
                                    it,
                                    allFriendUnreadCountList[it.fromAccount] ?: 0,
                                    allFriendsLoginStatus[it.fromAccount] ?: false
                                )
                            )
                        }
                        _mRecentContactList.emit(customRecentContactList)
                    }
                }
            }
        })
    }

}